package com.itdong.controller;

import com.itdong.domain.User;
import com.itdong.service.UserService;
import com.itdong.utils.WebUtils;
import com.itdong.vc.ResultVc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Slf4j
@RestController
public class UserCotroller {

    @Autowired
    private UserService userService;



    @GetMapping("/api/getAllUser")
    //@PreAuthorize("hasAuthority('admin')")
    public ResultVc getAllUser(){
        log.info("进入了getAllUser");
        List<User> allUser = userService.getAllUser();
        log.info(allUser.toString());
        return  new ResultVc(allUser, "获取成功");
    }

    /**
     * 登录成功
     * @return
     */
    @PostMapping("/api/login-success")
    public ResultVc loginSuccess(){
        //能进来这里的是登录成功了
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal == null){
            //就要重新登录
        }
        UserDetails userDetails = null;
        if (principal instanceof UserDetails){
            userDetails = (UserDetails) principal; //principal中只有username，password，authorities三个东西，而且密码为空
        }
        return new ResultVc(userDetails, "亲爱的"+userDetails.getUsername()+": 您已登录");
    }

    @PostMapping("/register")
    public ResultVc registerUser(@RequestBody User user){
        int i = userService.addNormUser(user);
        if (i > 0){
            //注册成功
            return new ResultVc(true, "注册成功");
        }else{
            return new ResultVc(false, "注册失败");
        }
    }

    @GetMapping("/loginByWeiXin/{code}")
    public ResultVc loginByWeiXin(@PathVariable String code){
        log.info(code);
        return new ResultVc(true, "微信登录成功");
    }

    @GetMapping("/testWebUtils")
    public void testWebUtils(HttpServletResponse response, HttpServletRequest request) throws Exception{
        ResultVc resultVc = new ResultVc("hello", "lin");
        WebUtils.responseJsonMsg(request, response, resultVc);
    }

}
